package pl.edu.agh.neuraleconomy.persistence.utils;

import java.sql.SQLException;

import org.apache.log4j.Logger;

import pl.edu.agh.neuraleconomy.common.configuration.Configuration;
import pl.edu.agh.neuraleconomy.model.base.IModel;
import pl.edu.agh.neuraleconomy.model.exchange.Company;
import pl.edu.agh.neuraleconomy.model.exchange.Currency;
import pl.edu.agh.neuraleconomy.model.exchange.Exchange;
import pl.edu.agh.neuraleconomy.model.simulation.DailyHistory;
import pl.edu.agh.neuraleconomy.model.simulation.Share;
import pl.edu.agh.neuraleconomy.model.simulation.Simulation;
import pl.edu.agh.neuraleconomy.model.simulation.Transaction;

import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DBUtils {
	private static ConnectionSource connSrc = null;
	private static Logger logger = Logger.getLogger(DBUtils.class);
	
	public static ConnectionSource getConnectionSource(){
		if(connSrc == null){
			try {
				connSrc = new JdbcConnectionSource(Configuration.getConnectionUrl());
			} catch (SQLException e) {
				logger.fatal("", e);
			}
		}
		return connSrc;
	}
	
	public static void createTable(Class<? extends IModel> clazz){
		try {
			TableUtils.dropTable(getConnectionSource(), clazz, true);
			TableUtils.createTable(getConnectionSource(), clazz);
		} catch (SQLException e) {
			logger.error("", e);
		}
	}
	
	public static void dropTable(Class<? extends IModel> clazz){
		try {
			TableUtils.dropTable(getConnectionSource(), clazz, true);
		} catch (SQLException e) {
			logger.error("", e);
		}
	}
	
	public static void dropAllTables(){
		dropTable(Exchange.class);
		dropTable(Currency.class);
		dropTable(Company.class);
	}
	
	public static void createAllTables(){
		createTable(Currency.class);
		createTable(Company.class);
		createTable(Exchange.class);
	}
	
	public static void createAllSimulationTables(){
		createTable(Simulation.class);
		createTable(DailyHistory.class);
		createTable(Share.class);
		createTable(Transaction.class);
	}
}
